<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of UserController
 *
 * @author QuangKhoi
 */
class UserController {
    //put your code here
    
    private $model;
    private $view;
    
    public function __construct($model, $view) {
        $this->model = $model;
        $this->view = $view;
    }
    
    public function save() {
        $db = Database::getInstance();
        if ($this->model->idUser == null) {
            //Create new
            $token = "";
            $tokenexp = "";
            $model = $this->model;
            $model->idUser = Database::getID("Users", "idUser");
            $query = "INSERT INTO Users VALUES('$model->idUser'," .
                    " '$model->idAvatar', '$model->idDevice', '$token'," .
                    " '$tokenexp', '$model->nameUser', '$model->password'," .
                    " '$model->email', '$model->status')";
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                $this->view->status = new Status();
                $this->view->status->code = 200;
                $this->view->status->message = "Registration completed";
                $this->view->result = $this->model;
                $this->view->display("jsonView.php");
            }
            else {
                $controller = new ErrorController(new Error(), new ErrorView(), 
                        $result->returnCode, $result->returnMessage);
                $controller->returnError();
            }
        }
        else {
            //Update
        }
    }
    
    public function delete() {
        
    }
    
    public function login($password) {
        if ($password == $this->model->password) {
            $this->view->status = new Status();
            $this->view->status->code = 200;
            $this->view->status->message = "Login successfully";
            $this->view->result = $this->model;
            $this->view->display("jsonView.php");
        }
        else {
            $controller = new ErrorController(new Error(), new ErrorView, 
                "401", "Wrong password");
            $controller->returnError();
        }
    }
}

?>
